﻿using SignalGenLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace AgilentDemo
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 连接信号源
        /// </summary>
        private Socket _newclient;
        /// <summary>
        /// 信号源控制类
        /// </summary>
        private AglientSignalSourceCtrol _aglientCtrol;

        private delegate string ConnectSocketDelegate(IPEndPoint ipep, Socket sock);

        public Form1()
        {
            InitializeComponent();

            _aglientCtrol = new AglientSignalSourceCtrol();

            //this.Width = 514;
            //this.Height = 356;

            //SignalPlot memberinfo = new SignalPlot();
            //memberinfo.Show();
            //memberinfo.Focus();

        }


        private string ConnectSocket(IPEndPoint ipep, Socket sock)
        {
            string exmessage = "";
            try
            {
                sock.Connect(ipep);
            }
            catch (System.Exception ex)
            {
                exmessage = ex.Message;
            }
            finally
            {
            }
            return exmessage;
        }

        // 连接
        private void btnConnect_Click(object sender, EventArgs e)
        {
            string ipStr = ipEt.Text;

            if (ipStr == null || !Regex.IsMatch(ipStr, @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$", RegexOptions.IgnoreCase)) 
            {
                MessageBox.Show("请输入正确的ip！");
                return;
            }
            _newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipStr), 5025);
            try
            {
                //_newclient.Connect(ie);
                ConnectSocketDelegate connect = ConnectSocket;
                IAsyncResult asyncResult = connect.BeginInvoke(ie, _newclient, null, null);

                bool connectSuccess = asyncResult.AsyncWaitHandle.WaitOne(2000, false); //2秒后结束
                if (!connectSuccess)
                {
                    MessageBox.Show(string.Format("连接失败！错误信息：{0}", "连接超时"));//2秒后弹出
                    return;
                }
                comboBox2.SelectedIndex = 0;
                MessageBox.Show("连接信号源成功！");
            }
            catch (SocketException)
            {
                MessageBox.Show("连接信号源失败！");
            }
        }

        // 断开
        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            try
            {
                if (_newclient != null)
                {
                    _newclient.Disconnect(true);
                }
            }
            catch (SocketException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnRefreshData_Click(object sender, EventArgs e)
        {
            float fre = Convert.ToSingle(txtFrequecy.Text);
            float amp = Convert.ToSingle(txtAmplitude.Text);
            float delay = Convert.ToSingle(txtDelay.Text);
            sendSingnalCmd(fre, amp, delay);
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox2.SelectedIndex == 0)
            {
                comboBox1.Items.Clear();
                comboBox1.Items.Add("CARDIAC.arb");
                comboBox1.Items.Add("D_LORENTZ.arb");
                comboBox1.Items.Add("EXP_FALL.arb");
                comboBox1.Items.Add("EXP_RISE.arb");
                comboBox1.Items.Add("GAUSSIAN.arb");
                comboBox1.Items.Add("HAVERSINE.arb");
                comboBox1.Items.Add("LORENTZ.arb");
                comboBox1.Items.Add("NEG_RAMP.arb");
                comboBox1.Items.Add("SINC.arb");
                comboBox1.Items.Add("ARB_hht1.arb");
            }
            else
            {
                comboBox1.Items.Clear();
                comboBox1.Items.Add("0001.arb");
                comboBox1.Items.Add("0002.arb");
                comboBox1.Items.Add("0003.arb");
                comboBox1.Items.Add("0004.arb");
                comboBox1.Items.Add("0005.arb");
                comboBox1.Items.Add("0006.arb");
            }
            comboBox1.SelectedIndex = 0;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (_newclient == null)
                return;

            float freq = Convert.ToSingle(txtFrequecy.Text);
            float amp = Convert.ToSingle(txtAmplitude.Text);
            float off = Convert.ToSingle(txtOffset.Text);
            float delay = Convert.ToSingle(txtDelay.Text);
            float rate = Convert.ToSingle(txtRate.Text);

            string str = "DATA:VOL:CLEAR\r\n";  // 清空内存中所有任意波形（默认保留EXP_RISE.arb）

            string wave = string.Format(@"INT:\{0}\{1}", comboBox2.SelectedItem.ToString(), comboBox1.SelectedItem.ToString());
            if(chkCustom.Checked)
            {
                wave = string.Format(@"INT:\{0}", txtCustomPath.Text.Trim());
            }

            str += string.Format("MMEM:LOAD:DATA \"{0}\"\r\n", wave);   // 加载任意波形到内存
            str += "FUNC ARB\r\n";
            str += string.Format("VOLT {0}\r\n", amp);              // Vpp
            str += string.Format("VOLT:UNIT {0}\r\n", "Vpp");
            str += string.Format("VOLTage:OFFSet {0}\r\n", off);    // Vpp
            str += string.Format("FUNC:ARB:SRAT {0}\r\n", rate);    // Sa/s
            str += string.Format("FUNCtion:ARBitrary \"{0}\"\r\n", wave);

            byte[] data = new byte[str.Length];
            data = Encoding.UTF8.GetBytes(str);
            _newclient.Send(data);
        }

        // 恢复上次内存
        private void button1_Click(object sender, EventArgs e)
        {
            string str = "MMEM:LOAD:ALL \"INT:\\MYARBS\\MySetup.all\"\r\n";

            byte[] data = new byte[str.Length];
            data = Encoding.UTF8.GetBytes(str);
            _newclient.Send(data);
        }

        // 保存本次内存
        private void button2_Click(object sender, EventArgs e)
        {
            string str = "MMEM:STOR:ALL \"INT:\\MYARBS\\MySetup.all\"\r\n";

            byte[] data = new byte[str.Length];
            data = Encoding.UTF8.GetBytes(str);
            _newclient.Send(data);
        }

        // 删除某个任意波形
        private void button4_Click(object sender, EventArgs e)
        {
            string temp = @"INT:\TEMPARB.ARB";
            string str = string.Format("MMEM:DELETE \"{0}\"\r\n", temp);

            byte[] data = new byte[str.Length];
            data = Encoding.UTF8.GetBytes(str);
            _newclient.Send(data);
        }

        // 清空内存波形
        private void button5_Click(object sender, EventArgs e)
        {
            string str = "DATA:VOL:CLEAR\r\n";

            byte[] data = new byte[str.Length];
            data = Encoding.UTF8.GetBytes(str);
            _newclient.Send(data);
        }

        // 设置电压
        private void button14_Click(object sender, EventArgs e)
        {
            if (_newclient == null)
                return;

            float volt = Convert.ToSingle(txtAmplitude.Text);
            string str = string.Format("VOLT +{0}\r\n", volt);
            str += "OUTP 1\r\n";
            byte[] data = new byte[str.Length];
            data = Encoding.UTF8.GetBytes(str);
            _newclient.Send(data);
        }

        // 下载波形
        private void button15_Click(object sender, EventArgs e)
        {
            string str = "DATA:VOL:CLEAR\r\n";  // 清空内存中所有任意波形（默认保留EXP_RISE.arb）

            //string temp = @"USB:\0002.arb";
            string wave = @"INT:\TEMPARB.arb";
            str += string.Format("MMEM:DOWN:FNAM \"{0}\"\r\n", wave);        

            StreamReader sr = new StreamReader("ARB_001.arb");
            string mydata = sr.ReadToEnd();
            int length = mydata.Length;
            sr.Close();
            str += string.Format("MMEM:DOWN:DATA #{0}{1}{2}\r\n", length.ToString().Length, length, mydata);
            str += string.Format("MMEM:LOAD:DATA \"{0}\"\r\n", wave);   // 加载任意波形到内存
            str += string.Format("FUNCtion:ARBitrary \"{0}\"\r\n", wave);

            byte[] data = new byte[str.Length];
            data = Encoding.UTF8.GetBytes(str);
            _newclient.Send(data);
        }


        /// <summary>
        /// 发送信号源命令
        /// </summary>
        /// <param name="freq"></param>
        /// <param name="amp"></param>
        /// <param name="delay"></param>
        private void sendSingnalCmd(float freq, float amp, float delay)
        {
            if (_newclient == null)
                return;

            string str = "FUNCtion SIN\r\n";
            str += string.Format("FREQuency {0}\r\n", freq);    // Hz
            str += string.Format("VOLT:UNIT {0}\r\n", "VPP");
            str += string.Format("VOLT {0}\r\n", amp);        // Vpp

            str += "BURS:MODE TRIG\r\n";
            str += string.Format("BURS:NCYC {0}\r\n", 5);
            str += "BURS:PHAS 0\r\n";
            str += "TRIG:SOUR EXT\r\n";
            str += string.Format("TRIG:DEL {0}e-6\r\n", delay); // 微秒
            if (chkTrig.Checked)    // 是否触发
            {
                str += "BURS:STAT ON\r\n";
            }
            else
            {
                str += "BURS:STAT OFF\r\n";
            }
            str += "OUTP 1\r\n";

            byte[] data = new byte[str.Length];
            data = Encoding.UTF8.GetBytes(str);
            _newclient.Send(data);
        }



        // 连接
        private void button8_Click(object sender, EventArgs e)
        {
            if (_aglientCtrol.ConnectDevice())
            {
                MessageBox.Show("连接成功");
            }
        }
        // 断开
        private void button9_Click(object sender, EventArgs e)
        {
            _aglientCtrol.DisConnectDevice();
        }
        // 更新数据
        private void button6_Click(object sender, EventArgs e)
        {
            int freq = Convert.ToInt32(txtFrequecy.Text);
            float volt = Convert.ToSingle(txtAmplitude.Text);
            int delay = Convert.ToInt32(txtDelay.Text);
            _aglientCtrol.TriggerSinWave(freq, volt, 5, delay);
        }
        // 测试
        private void button7_Click(object sender, EventArgs e)
        {
            float volt = Convert.ToSingle(txtAmplitude.Text);
            int delay = Convert.ToInt32(txtDelay.Text);
            int rate = Convert.ToInt32(txtRate.Text);
            string arbName = comboBox1.SelectedItem.ToString();

            _aglientCtrol.TriggerArbWave(arbName, rate, volt, 1, delay);
        }

        // 设置采样率及电压
        private void button10_Click(object sender, EventArgs e)
        {
            //int rate = Convert.ToInt32(txtRate.Text);
            //float volt = Convert.ToSingle(txtAmplitude.Text);

            //_aglientCtrol.SetParameters(rate, volt);
        }

        // 设置采样率
        private void button11_Click(object sender, EventArgs e)
        {
            int rate = Convert.ToInt32(txtRate.Text);

            _aglientCtrol.SetSampleRate(rate);
        }

        // 设置电压
        private void button12_Click(object sender, EventArgs e)
        {
            float volt = Convert.ToSingle(txtAmplitude.Text);

            _aglientCtrol.SetVoltage(volt);
        }

        // 设置延时
        private void button13_Click(object sender, EventArgs e)
        {

        }
    }
}
